const {parseString} = require('xml2js')
module.exports = class extends think.Service {
  constructor (...args) {
    super(...args)
    this.conf = think.config('wxopen')
  }
  /**
     * 刷新公众号token
     * @param appid 公众号
     * @returns {}
     */
  async refresh_access_token (appid = null) {
    let d = {}
    if (appid) {
      const component_access_token = await think.cache('component_access_token')
      const {refresh_token} = await yy.model('wx_authorizer').where({appid}).field('refresh_token').find()
      d = await yy.http.post(`https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=${component_access_token}`, {
        component_appid: this.conf.appid,
        authorizer_appid: appid,
        authorizer_refresh_token: refresh_token
      })
      if (d.authorizer_access_token && d.authorizer_refresh_token) {
        // 增加公众号token 缓存以及过期时间
        await think.cache(`access_token_${appid}`, d.authorizer_access_token, {type: 'file', file: {timeout: 5900 * 1000}})
        await yy.model('wx_authorizer').where({appid}).update({refresh_token: d.authorizer_refresh_token})
      }
    }
    return d
  }
  /**
     * 根据id获取公众号
     * @param id
     * @returns {*}
     */
  async get_appid_by_id (id) {
    let authorizer = await think.cache(`wx_authorizer_${id}`)
    if (!authorizer.appid) {
      authorizer = await yy.model('wx_authorizer').where({id: id}).find()
      if (authorizer.appid) await think.cache(`wx_authorizer_${id}`, authorizer)
    }
    return authorizer.appid
  }

  async get_authorizer_by_id (id) {
    let authorizer = await think.cache(`wx_authorizer_${id}`)
    if (!authorizer.appid) {
      authorizer = await yy.model('wx_authorizer').where({id: id}).find()
      if (authorizer.appid) await think.cache(`wx_authorizer_${id}`, authorizer)
    }
    return authorizer || {}
  }

  /**
     * 获取公众号token
     * @param appid
     * @returns {*}
     */
  async get_access_token (appid = null) {
    let token = await think.cache(`access_token_${appid}`)
    if (!token) {
      const d = await this.refresh_access_token(appid)
      token = d.authorizer_access_token
      yy.log.debug(d)
    }
    return token
  }

  /**
     * xml转义json
     * @param xml
     * @returns {Promise}
     */
  xmlformat (xml) {
    return new Promise((resolve, reject) => {
      parseString(xml, {trim: true, explicitArray: false}, (e, d) => {
        if (e)reject(e)
        resolve((d && d.xml) ? d.xml : false)
      })
    })
  }

  /**
   * post数据转义json
   * @param http
   * @returns {Promise}
   */
  async xmlPost (http) {
    const payload = (http.getPayload) ? await http.getPayload() : http.payload
    const cb = await this.xmlformat(payload)
    return cb
  }
}
